# 处理txt，excel，yaml，json文件
# txt

# 文件对象,读文件    r:反转义
import os.path

import openpyxl
from openpyxl import Workbook
from openpyxl.worksheet.worksheet import Worksheet

fileName=r'D:\work\codings\python\2506pro\autoOne\datas'
# 换行  '/n'
# f=open(fileName,encoding='utf-8')
# print(f,type(f))
# print(f.read())

class DoFile():
    def doTxtRead(self):
        # 文件对象,读文件    r:反转义
        fileName = r'D:\work\codings\python\2506pro\homeWorkPro\myDate\myDate.txt'
        # 换行  '/n'
        f = open(fileName, encoding='utf-8')
        print(f, type(f))
        print(f.read())
        # 关闭
        f.close()

        # 当代码离开with体之后，自动调用close，即自动关闭
        # r+：代表以读的形式打开文件，且拥有写的权限
        # w+：代表以写的形式打开文件，且拥有读的权限
        # 写的形式：先清空文件，再做其他处理
        with open(fileName, mode='r+',encoding='utf-8') as f:
            print(f, type(f))
            print(f.read())
            f.write('xixi')
            print(f.read())

    def doTxtWrite(self,fname):
        fileName1=os.path.join(fileName,fname)
        f=open(fileName1,mode='a',encoding='utf-8')
        # 写
        f.write('晚安图图')
        f.close()

#         图片
    def doPNGRead(self, fname):
        fileName1=os.path.join(fileName,fname)
        with open(fileName1,mode='r+b')as f:
            print(f,type(f))
            myPNG=f.read()
            return myPNG
    def doPNGWrite(self,fname,strs):
        fileName1=os.path.join(fileName,fname)
        with open(fileName1,mode='w+b')as f:
            f.write(strs)




    # 处理Excel文件，读，写
    def doExcelReadDIV(self,fname,stname,minRow=None,maxRow=None,minCol=None,maxCol=None):
        fileName1=os.path.join(fileName,fname)
        wk:Workbook=openpyxl.load_workbook(fileName1)
        st:Worksheet=wk[stname]
        print(st,type(st))
        ss=st.iter_rows(min_row=minRow,
                        max_row=maxRow,
                        min_col=minCol,
                        max_col=maxCol,
                        values_only=True)
        l=[i for i in ss]   #采用列表推导式
        print(f'{l}')
        return l



#     写excel文件
    def doExcelWrite(self,fname,stname,ss):
        fileName1=os.path.join(fileName,fname)
        # 创建新文件
        wk=openpyxl.Workbook()
        # 创建sheet对象
        st:Worksheet=wk.create_sheet(stname,1)
        # 写一个单元格
        st.cell(1,1,ss)
        # 保存
        wk.save(fileName1)

if __name__ == '__main__':
    df = DoFile()

    # # df.doExcelReadDIV('yl.xlsx', "Sheet1", 1, 2, 2, 6)
    # df.doExcelWrite('yl1.xlsx','Sheet4','hello,python')
    # 1.
    # 在doFile中测试模块
    # 读取测试用例中的数据
    df.doExcelReadDIV('gz.xlsx','Sheet1',2,18,1,4)



    # 调用函数
    # 获取一个文件的内容
    # sss=df.doPNGRead()
    # fileName='phote3.jpg'
    # # 写一个文件
    # df.doPNGWrite(fileName,sss)



